/**
 * 20. 有效的括号
 * https://leetcode-cn.com/problems/valid-parentheses/
 */

const smallLeft = 40;
const smallRight = 41;
const mediumLeft = 91;
const mediumRight = 93;
const bigLeft = 123;
const bigRight = 125;

/**
 * @param {string} s
 * @return {boolean}
 */
function isValid(s) {
  const { length } = s;
  const stack = new Array(length);
  let top = -1;
  for (let i = 0; i < length; i += 1) {
    const code = s.charCodeAt(i);
    const topNum = stack[top];
    let isUse = false;
    switch (topNum) {
      case smallLeft:
        isUse = code === smallRight;
        break;
      case mediumLeft:
        isUse = code === mediumRight;
        break;
      case bigLeft:
        isUse = code === bigRight;
        break;
      default:
        break;
    }
    if (isUse) {
      top -= 1;
    } else {
      top += 1;
      stack[top] = code;
    }
  }
  return top < 0;
}

console.log(isValid('()') === true);
console.log(isValid('()[]{}') === true);
console.log(isValid('(]') === false);
console.log(isValid('([)]') === false);
console.log(isValid('{[]}') === true);
